import 'dart:async';

import 'package:flutter/services.dart';
import 'package:shop/common/AppStorge.dart';
import 'package:shop/common/shop_material.dart';
import 'package:shop/service/MemberService.dart';
import 'package:shop/utils/MyToast.dart';

class SendCode extends StatefulWidget {
  final String phone;
  SendCode({Key key, this.phone}) : super(key: key);
  @override
  _SendCodeState createState() => _SendCodeState();
}

class _SendCodeState extends State<SendCode> {
  MemberService memberService = MemberService();

  FocusNode focusNode1 = FocusNode();
  FocusNode focusNode3 = FocusNode();
  FocusNode focusNode2 = FocusNode();
  FocusNode focusNode4 = FocusNode();
  int index = 60;
  TextEditingController textEditingController1 = TextEditingController();
  TextEditingController textEditingController2 = TextEditingController();
  TextEditingController textEditingController3 = TextEditingController();
  TextEditingController textEditingController4 = TextEditingController();
  Timer timer;
  @override
  void initState() {
    super.initState();
    _initGetData();
    timer = Timer.periodic(Duration(seconds: 1), (t) {
      if (index > 0) {
        setState(() {
          index--;
        });
      }
    });
  }

  //发送验证码
  _initGetData() async {
    bool res = await memberService.sendSms(widget.phone);
    if (res) index = 60;
  }

  //登录接口
  _login() async {
    String smscode = textEditingController1.text +
        textEditingController2.text +
        textEditingController3.text +
        textEditingController4.text;
    bool res = await memberService.register(widget.phone, smscode);
    if (res) {
      Map loginStorge = MyStorge.login;
      loginStorge["${widget.phone}"] = {
        'password': "",
        'img': "",
      };
      loginStorge["def"] = widget.phone;
      MyStorge.login = loginStorge;
      route.pop();
    } else {
      //清空
      textEditingController1.text = "";
      textEditingController2.text = "";
      textEditingController3.text = "";
      textEditingController4.text = "";
      FocusScope.of(context).requestFocus(focusNode1);
      MyToast("验证码不正确");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 0,
        leading: InkWell(
          onTap: () => route.pop(),
          child: Icon(Icons.arrow_back_ios),
        ),
      ),
      body: GestureDetector(
        onTap: () => FocusScope.of(context).requestFocus(FocusNode()),
        child: Container(
          padding: EdgeInsets.all(40.w),
          color: Colors.white,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              SizedBox(height: 30.h),
              Text("输入验证码",
                  style: TextStyle(fontSize: 42.s, color: Color(0xFF333333))),
              SizedBox(height: 15.h),
              Row(
                children: <Widget>[
                  Text(
                    "验证码已发送至 ",
                    style: TextStyle(fontSize: 24.s, color: Color(0xFF333333)),
                  ),
                  Text(
                    "+86 ${widget.phone.substring(0, 3)} ${widget.phone.substring(3, 7)} ${widget.phone.substring(7, 11)}",
                    style: TextStyle(fontSize: 32.s, color: Color(0xFF333333)),
                  ),
                ],
              ),
              SizedBox(height: 80.h),
              Row(
                children: <Widget>[
                  textfield(focusNode1, textEditingController1, (str) {
                    if (str.length == 1)
                      FocusScope.of(context).requestFocus(focusNode2);
                  }),
                  textfield(focusNode2, textEditingController2, (str) {
                    if (str.length == 1)
                      FocusScope.of(context).requestFocus(focusNode3);
                    else
                      FocusScope.of(context).requestFocus(focusNode1);
                  }),
                  textfield(focusNode3, textEditingController3, (str) {
                    if (str.length == 1)
                      FocusScope.of(context).requestFocus(focusNode4);
                    else
                      FocusScope.of(context).requestFocus(focusNode2);
                  }),
                  textfield(focusNode4, textEditingController4, (str) {
                    if (str.length >= 1) {
                      _login();
                    } else {
                      FocusScope.of(context).requestFocus(focusNode3);
                    }
                  }),
                ],
              ),
              Container(
                margin: EdgeInsets.only(left: 30.w, right: 30.w),
                child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: List.generate(
                        4,
                        (index) => Container(
                            width: 100.w, color: Colors.grey, height: 1))),
              ),
              SizedBox(height: 50.h),
              index > 0
                  ? Text("重新发送($index)",
                      style:
                          TextStyle(color: Color(0xFF999999), fontSize: 24.s))
                  : InkWell(
                      onTap: _initGetData,
                      child: Text("发送验证码",
                          style: TextStyle(
                              color: Color(0xFF00C657), fontSize: 24.s)),
                    ),
            ],
          ),
        ),
      ),
    );
  }

  Widget textfield(focusNode, textEditingController, onchange) {
    return Expanded(
      child: TextField(
        textAlign: TextAlign.center,
        maxLength: 1,
        controller: textEditingController,
        autofocus: true,
        focusNode: focusNode,
        keyboardType: TextInputType.number,
        inputFormatters: [WhitelistingTextInputFormatter.digitsOnly],
        style: TextStyle(
          fontSize: 42.s,
        ),
        decoration: InputDecoration(
          contentPadding: EdgeInsets.only(bottom: 6.h),
          counterText: "",
          border: InputBorder.none,
        ),
        onChanged: onchange,
      ),
    );
  }

  @override
  void dispose() {
    textEditingController1.dispose();
    textEditingController2.dispose();
    textEditingController3.dispose();
    textEditingController4.dispose();
    super.dispose();
    timer.cancel();
    timer = null;
  }
}
